package com.jinlejia.erp.ui.new_house.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.ActivityRecommedValidBinding;
import com.jinlejia.erp.ui.new_house.adapter.ApplyAdapter;
import com.jinlejia.erp.ui.new_house.apply.VisitApplyActivity;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;


/**
 * 有效列表
 */
public class RecommendValidActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {
    private ApplyAdapter adapter;
    private int page = 1;
    private boolean mLoadingLock = false;
    private String type;
    private ActivityRecommedValidBinding binding;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_recommed_valid);
        EventBus.getDefault().register(this);
        initViews();
        getData();
        initEvents();
    }


    protected void initViews() {
        if (getIntent().hasExtra("type") && !TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            type = getIntent().getStringExtra("type");
        }
        binding.recyclerView.setHasFixedSize(true);
        binding.recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        binding.recyclerView.enableAutoLoadMore(this);
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        ArrayList<Map<String, String>> dataList = new ArrayList<>();
        adapter = new ApplyAdapter(dataList);
        binding.recyclerView.setAdapter(adapter);
    }

    private void getData() {
        if (type.equals("0")) {//带访
            binding.titleText.setText("推荐有效列表");
            getRecommendValid();
        } else if (type.equals("1")) {//复访
            binding.titleText.setText("带访有效列表");
            getReVisit();
        }
    }

    protected void initEvents() {
        binding.idBack.setOnClickListener(v -> finish());
        adapter.setOnItemClickListener((view, o) -> {
            Map<String, String> map = (Map<String, String>) o;
            Intent intent = new Intent(RecommendValidActivity.this, VisitApplyActivity.class);
            intent.putExtra("customerName", map.get("customerName"));
            intent.putExtra("customerTel", map.get("customerTel"));
            intent.putExtra("houseName", map.get("houseName"));
            intent.putExtra("type", getIntent().getStringExtra("type"));
            if (type.equals("0")) {
                intent.putExtra("recommendCode", map.get("recommendCode"));
            } else if (type.equals("1")) {
                intent.putExtra("accessCode", map.get("accessCode"));
            }
            startActivity(intent);
        });
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        mLoadingLock = true;
        page++;
        getData();
    }

    private void getRecommendValid() {
        OkHttpUtils.get().url(String.format(ApiConfig.RECOMMEND_VALID, page))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(RecommendValidActivity.this, response, adapter)) {
                            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(response.get("data").toString());
                            ArrayList<Map<String, String>> dataList = JSON.parseObject(jsonArray.toJSONString(), new TypeReference<ArrayList<Map<String, String>>>() {
                            });

                            if (page == 1) {
                                adapter.setData(dataList);
                            } else if (page > 1 && !adapter.mData.containsAll(dataList)) {
                                adapter.addData(dataList);
                            } else {
                                page--;
                            }
                        }
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    private void getReVisit() {
        OkHttpUtils.get().url(String.format(ApiConfig.RE_VISIT_LIST, page))
                .addParams("state", "1")
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(RecommendValidActivity.this, response, adapter)) {
                            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(response.get("data").toString());
                            ArrayList<Map<String, String>> dataList = JSON.parseObject(jsonArray.toJSONString(), new TypeReference<ArrayList<Map<String, String>>>() {
                            });

                            if (page == 1) {
                                adapter.setData(dataList);
                            } else if (page > 1 && !adapter.mData.containsAll(dataList)) {
                                adapter.addData(dataList);
                            } else {
                                page--;
                            }
                        }
                        mLoadingLock = false;
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                    }
                });
    }

}
